/* global Slick, nf */

$(document).ready(function () {
    ua.init();
    
    $('#thenRule').combobox({
        onChange: function (selVal, o) {
        	if(selVal == 'equals'){
        		var spanStr = "<input name='thenVal' class='form-control' type='text' style='width:250px; display:inline;'  placeholder=''> ";
        		$("td[name='thenValTd']").html(spanStr);
        		$("td[name='btnTd']").show();
        	}
        	else{ // replace
        		var spanStr = "<span>" + 
        					  "  <input name='oldChar' class='form-control' type='text' style='width:120px; display:inline;'  placeholder='原字符'> - " +
        				      "  <input name='newChar' class='form-control' type='text' style='width:120px; display:inline;'  placeholder='新字符'> " + 
        					  "  <input type='button' value='添加' class='btn btn-ok' onclick='addReplaceInput()'> " + 
        					  "</span>";
        		$("td[name='thenValTd']").html(spanStr);
        		$("td[name='btnTd']").show();
        	}
        }
    });
    
});
var editIndex = undefined;

var ua = {
    editable: true,
    
    /**
     * Initializes this web application.
     * 
     * @returns {undefined}
     */
    init: function () {
        var evaluationContext = $.ajax({
            type: 'GET',
            url: 'api/standard/processor/details?' + $.param({
                processorId: ua.getProcessorId()
            })
        }).done(function (ret) {
            
        	$('#processorName').val(ret['name']);
        	
        	var ruleJson = ret['properties']['ruleJson'];
            if(ruleJson!=undefined && ruleJson!=''){
            	
            	parseVal(ruleJson);
            }
        });
        
        $('#changeName').on('click', function (obj){
            var processorName = $('#processorName').val();
            var param = {
                "processorName": processorName
            };
            var urlParams = 'processorId='+ua.getProcessorId()+'&revisionId='+ua.getRevision()+'&clientId='+ua.getClientId();
            $.ajax({
                type: 'PUT',
                url: 'api/standard/processor/changeName?'+urlParams,
                data: JSON.stringify(param),
                processData: false,
                contentType: 'application/json'
            }).then(function (response) {
            	window.parent.HLplugin.refreshNfCanvas();
            }, function (xhr, status, error) {

            });
        });
        
    },
    /**
     * Gets the client id.
     * 
     * @returns 
     */
    getClientId: function () {
        return $('#attribute-updater-client-id').text();
    },
    
    /**
     * Gets the revision.
     * 
     * @returns 
     */
    getRevision: function () {
        return $('#attribute-updater-revision').text();
    },
    
    /**
     * Gets the processor id.
     * 
     * @returns
     */
    getProcessorId: function () {
        return $('#attribute-updater-processor-id').text();
    }
};


//生成json
function save(){
	
	var ifField = $("input[name='ifField']").val();
	var ifRule = $("#ifRule").combobox("getValue");
	var ifVal = $("input[name='ifVal']").val();
	var ifJson = " \"if\": {\"field\":\"" + ifField + "\", \"rule\":\"" + ifRule + "\", \"val\":\"" + ifVal + "\"} ";
	
	var thenField = $("input[name='thenField']").val();
	var thenRule = $("#thenRule").combobox("getValue");
	var thenJson = " \"then\": {\"field\":\"" + thenField + "\", \"rule\":\"" + thenRule + "\", ";
	
	if(thenRule == 'equals'){
		thenJson += " \"val\":\"" + $("input[name='thenVal']").val() + "\" ";
	}
	else{ // replace
		var replaceJson = "";
		$("td[name='thenValTd']").find("span").each(function(index, item){
			var oldChar = $(item).find("[name='oldChar']").val();
			var newChar = $(item).find("[name='newChar']").val();
			
			replaceJson += ",\"" + oldChar + "\":\"" + newChar + "\"";
		});
		
		thenJson += "\"val\": {" + replaceJson.substr(1) + "}";
	}
	thenJson += "}";
	
	var ruleJson = "{ " + ifJson + ", " + thenJson + " }";
	
	var urlParams = 'processorId='+ua.getProcessorId()+'&revisionId='+ua.getRevision()+'&clientId='+ua.getClientId();
    var param = {
        "ruleJson" : ruleJson
    };
    
    $.ajax({
        type: 'PUT',
        url: 'api/standard/processor/properties?'+urlParams,
        data: JSON.stringify(param),
        processData: false,
        contentType: 'application/json'
    }).then(function (response) {
    	window.parent.HLplugin.refreshNfCanvas();
        $('#retValue').text("保存成功");
    }, 
    function (xhr, status, error) {
    });
}


//解析json
function parseVal(jsonStr){
	
	if(jsonStr != undefined && jsonStr != '') {
		
		var ruleJson = JSON.parse(jsonStr);
		
		var ifJson = ruleJson.if;
		$("input[name='ifField']").val( ifJson.field );
		$("#ifRule").combobox('setValue', ifJson.rule); 
		$("input[name='ifVal']").val( ifJson.val );
		
		var thenJson = ruleJson.then;
		$("input[name='thenField']").val( thenJson.field );
		$("#thenRule").combobox('setValue', thenJson.rule );
		if(thenJson.rule == 'equals'){
			$("input[name='thenVal']").val( thenJson.val )
		}
		else{ // replace
			var index = 0;
			var spanStr = "";
			$.each(thenJson.val, function(key, val){
				spanStr += "<span>" + 
						   "  <input name='oldChar' class='form-control' type='text' style='width:120px; display:inline;' value='" + key + "' > - " + 
						   "  <input name='newChar' class='form-control' type='text' style='width:120px; display:inline;' value='" + val + "' > " ;
				if(index == 0){
					spanStr += "  <input type='button' value='添加' class='btn btn-ok' onclick='addReplaceInput()'> " ;
				}
				else{
					spanStr += "  <input type='button' value='删除' class='btn btn-ok' onclick='delReplaceInput(this)'>" ;
				}
				spanStr += "</span>" ;
				
				index++;
			});
			$("td[name='thenValTd']").html(spanStr);
		}
	}
	
}


function addReplaceInput(){
	
	var spanStr = "<span>" + 
				  "  <input name='oldChar' class='form-control' type='text' style='width:120px; display:inline;'  placeholder='原字符'> - " + 
	              "  <input name='newChar' class='form-control' type='text' style='width:120px; display:inline;'  placeholder='新字符'> " + 
				  "  <input type='button' value='删除' class='btn btn-ok' onclick='delReplaceInput(this)'>" + 
				  "</span>";
				  
	$("td[name='thenValTd']").append(spanStr);
}


function delReplaceInput(obj){
	
	$(obj).parent().remove();
}


